package com.zhou.piledriver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhou.piledriver.mapper.PdWarningMapper;
import com.zhou.piledriver.mapper.PdWarningRuleMapper;
import com.zhou.piledriver.model.entity.PdDeviceRecord;
import com.zhou.piledriver.model.entity.PdWarning;
import com.zhou.piledriver.model.entity.PdWarningRule;
import com.zhou.piledriver.model.so.RecordSo;
import com.zhou.piledriver.model.so.SimpleSo;
import com.zhou.piledriver.service.PdPileService;
import com.zhou.piledriver.service.PdWarningService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhouShenBin
 * @date 2024/3/27 10:13
 * @description
 */
@Service
public class PdWarningServiceImpl implements PdWarningService {

@Resource
    PdWarningMapper pdWarningMapper;
@Resource
    PdWarningRuleMapper pdWarningRuleMapper;
@Resource
private PdPileService pdPileService;
    @Override
    public IPage<PdWarning> list(Page<PdWarning> page, RecordSo so) {
//        LambdaQueryWrapper<PdWarning> queryWrapper = new LambdaQueryWrapper<>();
//        return pdWarningMapper.selectPage(page, queryWrapper);
        List<Long> pileIds = new ArrayList<>();
        pileIds = pdPileService.listPilesByDevice(so);

        if(CollectionUtils.isEmpty(pileIds)){
            return page;
        }
        LambdaQueryWrapper<PdWarning> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PdWarning::getPileId, pileIds)
                .ge(StringUtils.isNotBlank(so.getStartTime()), PdWarning::getWarningTime, StringUtils.isNotBlank(so.getStartTime()) ? LocalDateTime.parse(so.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null)
                .le(StringUtils.isNotBlank(so.getEndTime()), PdWarning::getWarningTime, StringUtils.isNotBlank(so.getEndTime()) ? LocalDateTime.parse(so.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null)
                .orderByDesc(PdWarning::getWarningTime)
                .orderByDesc(PdWarning::getId);
        return pdWarningMapper.selectPage(page, queryWrapper);
    }

    @Override
    public IPage<PdWarningRule> rule(Page<PdWarningRule> page, SimpleSo so) {
        LambdaQueryWrapper<PdWarningRule> queryWrapper = new LambdaQueryWrapper<>();
        return pdWarningRuleMapper.selectPage(page, queryWrapper);
    }
}
